package com.jic.weamop.weBankAMOP.common.server;

import com.alibaba.fastjson.JSON;
import com.jic.weamop.weBankAMOP.common.dto.request.MessageRequest;
import lombok.extern.slf4j.Slf4j;
import org.bcos.channel.dto.ChannelRequest;
import org.bcos.channel.dto.ChannelResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class MessageService extends BaseService{

	@Value("${current.org}")
	private String currentOrg;

    /**
     * AMOP发送消息——仅供测试使用，请勿实际调用
     * @param to 发送的topic
     * @param serviceId 服务ID
     * @param message 消息
     * @return ChannelResponseApi
     */
	public ChannelResponse sendMessage(String to, String serviceId, String message) {
       String topic="bcces-wbms.0001";//下单接口topic


        Map map;
        map = new HashMap();
        map.put("cardCode","123123123123");
        map.put("serviceId","0002");
        map.put("sNo",UUID.randomUUID().toString().replaceAll("-", ""));
        map.put("cardPlatform","1");
        map.put("merchantId","123456789");



		ChannelRequest request = new ChannelRequest();
		request.setToTopic(topic); // 设置消息topic
		request.setMessageID(ContractServer.service.newSeq());
		request.setTimeout(50000); // 消息的超时时间

		request.setContent(JSON.toJSONString(map));
		ChannelResponse response = ContractServer.service.sendChannelMessage2(request); // 发送消息

		log.info("Get callback seq1:" + String.valueOf(response.getMessageID()) + ", ErrorCode:"
				+ response.getErrorCode() + ", Content:" + response.getContent()+",serviceId="+serviceId);
		return response;
	}


    /**
     * 发送消息接口——正式接口
     * @param messageRequest 消息请求入参实体类
     * @return ChannelResponseApi
     * @author taozhouchuan
     * @Date 2020-11-15 20:38:43
     */
    public ChannelResponse sendMessage(MessageRequest messageRequest) {
        try {
            ChannelRequest request = new ChannelRequest();
            request.setToTopic(messageRequest.getToTopic()); // 设置消息topic
            request.setMessageID(ContractServer.service.newSeq());
            request.setTimeout(messageRequest.getTimeOut()); // 消息的超时时间
            request.setContent(messageRequest.getMessage());

            log.info("==========消息接口，请求入参 = {}", JSON.toJSONString(request));
            ChannelResponse response = ContractServer.service.sendChannelMessage2(request); // 发送消息
            log.info("==========消息接口，请求出参 = {}", JSON.toJSONString(response));
            return response;
        }catch (Exception e){
            e.printStackTrace();
            log.error("======接口异常======",e.getMessage());
            ChannelResponse response = new ChannelResponse();
            response.setErrorCode(9999);
            response.setErrorMessage(e.getMessage());
            return response;
        }
    }

}
